defmodule EliPhxPlayWeb.Components.DashboardRight.ContactsComponent do
  use EliPhxPlayWeb, :live_component
  alias EliPhxPlay.Context.Accounts
  alias EliPhxPlay.Context.UserRelationship
  alias Phoenix.PubSub

  def mount(socket) do
  # 订阅当前用户的通知（如果已连接且有用户ID）


  {:ok, assign(socket,
    show_add_friend_modal: false,
    search_term_addf: "",
    search_results: [],
    selected_user: nil,
    show_notification: false,
    notification_type: nil,
    notification_message: "",
    notification_timer: nil,
    friends_requests_modal: false,
    friend_requests: [],  # 添加好友请求列表
  )}
end

def update(assigns, socket) do
  socket = assign(socket, assigns)

  # 如果已连接且有用户ID，订阅通知
  if connected?(socket) and assigns[:user_id] do
    Phoenix.PubSub.subscribe(EliPhxPlay.PubSub, "user_notifications:#{assigns.user_id}")
  end

  {:ok, socket}
end


  def render(assigns) do
    ~H"""
    <div class="h-full bg-white flex flex-col">

      <%= render_contacts_header(assigns) %>


      <!-- 联系人列表 - 可滚动区域 -->
      <div class="flex-1 overflow-y-auto">
        <%= if length(@contacts) > 0 do %>
          <div class="divide-y divide-gray-200">
            <%= for contact <- @contacts do %>
              <div class="p-4 hover:bg-gray-50 transition-colors duration-200">
                <div class="flex items-center justify-between">
                  <div class="flex items-center space-x-4">
                    <!-- 头像 -->
                    <div class="flex-shrink-0">
                      <%= if contact.user_avatar_url do %>
                        <img class="h-10 w-10 rounded-full object-cover" src={contact.user_avatar_url} alt={contact.user_nickname || contact.user_account}>
                      <% else %>
                        <div class="h-10 w-10 rounded-full bg-gradient-to-r from-blue-500 to-purple-600 flex items-center justify-center">
                          <span class="text-sm font-medium text-white font-bold">
                            <%= String.first(contact.user_nickname || contact.user_account || "?") %>
                          </span>
                        </div>
                      <% end %>
                    </div>

                    <!-- 用户信息 -->
                    <div class="flex-1 min-w-0">
                      <p class="text-sm font-medium text-gray-900 truncate">
                        <%= contact.user_nickname || contact.user_account %>
                      </p>
                      <p class="text-sm text-gray-500 truncate">
                        @<%= contact.user_account %>
                      </p>
                    </div>
                  </div>

                  <!-- 操作按钮 -->
                  <div class="flex items-center space-x-2">
                    <button
                      phx-click="start_chat"
                      phx-value-user-id={contact.user_b_id}
                      phx-target={@myself}
                      class="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200"
                    >
                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-3.582 8-8 8a8.955 8.955 0 01-4.126-.98L3 21l1.98-5.874A8.955 8.955 0 013 12c0-4.418 3.582-8 8-8s8 3.582 8 8z"></path>
                      </svg>
                      聊天
                    </button>

                    <button
                      phx-click="remove_contact"
                      phx-value-user-id={contact.user_b_id}
                      phx-target={@myself}
                      class="inline-flex items-center px-3 py-1.5 border border-gray-300 text-xs font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200"
                    >
                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                      </svg>
                      删除
                    </button>
                  </div>
                </div>
              </div>
            <% end %>
          </div>
        <% else %>
          <div class="flex flex-col items-center justify-center h-full text-gray-500 p-8">
            <svg class="w-16 h-16 mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
            </svg>
            <p class="text-lg mb-2 text-gray-600">还没有联系人</p>
            <p class="text-sm text-gray-400">点击上方"添加好友"开始建立联系吧！</p>
          </div>
        <% end %>
      </div>

    </div>
    """
  end


    # 联系人页面标题
  defp render_contacts_header(assigns) do
    ~H"""
    <div class="bg-white border-b border-gray-200 px-6 py-4 flex-shrink-0">
      <div class="flex items-center justify-between gap-6">
        <!-- 标题区域 -->
        <div class="flex items-center gap-3">
          <h1 class="text-2xl font-bold text-gray-900">联系人</h1>
          <span class="bg-gray-100 text-gray-600 text-xs font-medium px-2.5 py-1 rounded-full">
            <%= if @contacts, do: length(@contacts), else: 0 %>
          </span>
        </div>

        <!-- 搜索框区域 -->
        <div class="relative flex-1 max-w-md min-w-0">
          <div class="absolute inset-y-0 left-0 pl-2 sm:pl-3 flex items-center pointer-events-none">
            <svg class="w-4 h-4 sm:w-5 sm:h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
            </svg>
          </div>
          <input
            type="text"
            placeholder="搜索联系人..."
            phx-target={@myself}
            phx-keyup="search"
            phx-debounce="300"
            class="block w-full pl-8 sm:pl-10 pr-3 sm:pr-4 py-2.5 sm:py-3 text-sm sm:text-base border border-gray-300 rounded-lg bg-gray-50 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:bg-white transition-all duration-200 placeholder-gray-400"
          />
        </div>

        <!-- 操作按钮区域 -->
        <div class="flex items-center gap-3">
          <button
            phx-target={@myself}
            phx-click="add_friend"
            class="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 focus:ring-4 focus:ring-blue-200 text-white px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 shadow-sm hover:shadow"
          >
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            添加好友
          </button>
        </div>
        <%!-- 添加好友 --%>
        <!-- Modal -->
        <%= if @show_add_friend_modal do %>
          <div class="fixed inset-0 z-50 overflow-y-auto">
            <!-- 背景遮罩 -->
            <div
              class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
              phx-click="close_modal"
              phx-target={@myself}
            ></div>

            <!-- Modal 内容 -->
            <div class="flex min-h-full items-center justify-center p-4">
              <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full">
                <!-- Modal 头部 -->
                <div class="flex items-center justify-between p-6 border-b">
                  <h3 class="text-lg font-semibold text-gray-900">添加好友</h3>
                  <button
                    phx-click="close_modal"
                    phx-target={@myself}
                    class="text-gray-400 hover:text-gray-600"
                  >
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                  </button>
                </div>

                <!-- Modal 内容 -->
                <div class="p-6">
                    <div class="mb-4">
                      <label class="block text-sm font-medium text-gray-700 mb-2">
                        用户昵称或账号
                      </label>
                      <input
                        type="text"
                        name="friend_identifier"
                        phx-keyup="search_users"
                        phx-debounce="300"
                        phx-target={@myself}
                        value={@search_term_addf || ""}
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="用户昵称或账号"
                        required
                      />

                      <!-- 搜索结果显示 -->
                      <%= if @search_results && length(@search_results) > 0 do %>
                        <div class="mt-2 bg-white border border-gray-300 rounded-md shadow-lg max-h-48 overflow-y-auto">
                          <%= for user <- Enum.reverse(@search_results) do %>
                            <div class="px-4 py-2 hover:bg-gray-50 border-b last:border-b-0 flex items-center justify-between">
                              <div class="flex-1">
                                <div class="font-medium"><%= user.nickname %></div>
                                <div class="text-sm text-gray-500">@<%= user.account %></div>
                              </div>
                              <button
                                class="ml-3 px-3 py-1 bg-green-600 hover:bg-green-700 text-white text-sm rounded-md transition-colors"
                                phx-click="select_user"
                                phx-value-user-id={user.user_id}
                                phx-target={@myself}
                              >
                                添加好友
                              </button>
                            </div>
                          <% end %>
                        </div>
                      <% end %>

                    </div>

                </div>

              </div>
            </div>
          </div>
        <% end %>


        <div class="flex items-center gap-4">
          <button
            phx-target={@myself}
            phx-click="show_friend_requests"
            class="inline-flex items-center gap-2 bg-green-600 hover:bg-green-700 focus:ring-4 focus:ring-green-200 text-white px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 shadow-sm hover:shadow"
          >
            好友请求
            <span class="bg-gray-100 text-gray-600 text-xs font-medium px-2.5 py-1 rounded-full">
            <%=@pendingnum%>
          </span>
          </button>
        </div>

      </div>
    </div>

    <!-- 好友请求模态框 -->
    <%= if @friends_requests_modal do %>
      <div class="fixed inset-0 z-50 overflow-y-auto">
        <!-- 背景遮罩 -->
        <div
          class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
          phx-click="close_friend_requests_modal"
          phx-target={@myself}
        ></div>

        <!-- Modal 内容 -->
        <div class="flex min-h-full items-center justify-center p-4">
          <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full max-h-96">
            <!-- Modal 头部 -->
            <div class="flex items-center justify-between p-6 border-b">
              <h3 class="text-lg font-semibold text-gray-900">好友请求</h3>
              <button
                phx-click="close_friend_requests_modal"
                phx-target={@myself}
                class="text-gray-400 hover:text-gray-600"
              >
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>

            <!-- Modal 内容 -->
            <div class="p-6 max-h-64 overflow-y-auto">
              <%= if @friend_requests && length(@friend_requests) > 0 do %>
                <%= for request <- @friend_requests do %>
                  <div class="flex items-center justify-between p-3 border-b last:border-b-0 hover:bg-gray-50">
                    <div class="flex-1">
                      <div class="font-medium text-gray-900"><%= request.user_nickname %></div>
                      <div class="text-sm text-gray-500">@<%= request.user_account %></div>

                    </div>
                    <div class="flex gap-2">
                      <button
                        class="px-3 py-1 bg-green-600 hover:bg-green-700 text-white text-sm rounded-md transition-colors"
                        phx-click="accept_friend_request"
                        phx-value-request-id={request.relationship_id}
                        phx-value-user-a-id={request.user_a_id}
                        phx-target={@myself}
                      >
                        同意
                      </button>
                      <button
                        class="px-3 py-1 bg-gray-400 hover:bg-gray-500 text-white text-sm rounded-md transition-colors"
                        phx-click="reject_friend_request"
                        phx-value-request-id={request.relationship_id}
                        phx-target={@myself}
                      >
                        拒绝
                      </button>
                    </div>
                  </div>
                <% end %>
              <% else %>
                <div class="text-center py-8 text-gray-500">
                  <svg class="w-12 h-12 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                  </svg>
                  <p class="text-gray-500">暂无好友请求</p>
                </div>
              <% end %>
            </div>
          </div>
        </div>
      </div>
    <% end %>



    <!-- 通知弹窗 -->
    <%= if @show_notification do %>
      <div
        class="fixed inset-0 z-50 flex items-center justify-center pointer-events-none"
        phx-click="hide_notification"
        phx-target={@myself}
      >
        <div class={"px-6 py-4 rounded-lg shadow-lg text-white font-medium pointer-events-auto transform transition-all duration-300 cursor-pointer #{if @notification_type == :success, do: "bg-green-500", else: "bg-red-500"}"}>
          <%= @notification_message %>
          <button
            class="ml-2 text-white hover:text-gray-200"
            phx-click="hide_notification"
            phx-target={@myself}
          >
            ×
          </button>
        </div>
      </div>
    <% end %>

    """
  end


    # 事件处理函数
  def handle_event("search", %{"value" => search_term}, socket) do
    send(self(), {:search, search_term})
    {:noreply, socket}
  end

  # 打开添加好友模态框
  def handle_event("add_friend", _params, socket) do
    {:noreply, assign(socket, show_add_friend_modal: true)}
  end

  # 关闭添加好友模态框
  def handle_event("close_modal", _params, socket) do
    {:noreply, assign(socket, show_add_friend_modal: false)}
  end



    # 处理搜索事件
  def handle_event("search_users", %{"value" => search_term_addf}, socket) do
    search_term_addf = String.trim(search_term_addf)

    if String.length(search_term_addf) >= 2 do
      # 调用 Accounts.search_users 函数
      results = Accounts.search_users(search_term_addf)
      {:noreply, assign(socket, search_term_addf: search_term_addf, search_results: results)}
    else
      {:noreply, assign(socket, search_term_addf: search_term_addf, search_results: [])}
    end
  end

    # 处理用户选择
  def handle_event("select_user", %{"user-id" => friend_id}, socket) do
    IO.puts("=== 处理select_user事件 ===")
    current_user_id = socket.assigns.user_id
    IO.inspect({current_user_id, friend_id}, label: "用户ID")

    # 检查是否添加自己为好友
    if current_user_id == friend_id do
      {:noreply, show_notification(socket, :error, "不能添加自己为好友")}
    else
      case UserRelationship.create_user_relationship(%{
        user_a_id: current_user_id,
        user_b_id: friend_id,
        relationship_status: "pending"
      }) do
        {:ok, relationship} ->
          IO.puts("=== 成功创建关系 ===")
          IO.inspect(relationship)

        # 广播好友请求通知给接收方
          Phoenix.PubSub.broadcast(
            EliPhxPlay.PubSub,
            "user_notifications:#{friend_id}",
            {:new_friend_request, %{from_user_id: current_user_id, relationship_id: relationship.relationship_id}}
          )


          # 获取被添加用户的信息用于显示
          selected_user = Enum.find(socket.assigns.search_results, &(&1.user_id == friend_id))
          user_name = if selected_user, do: selected_user.nickname || selected_user.account, else: "该用户"

          {:noreply,
            socket
            |> assign(show_add_friend_modal: false, search_results: [], search_term_addf: "", selected_user: nil)
            |> show_notification(:success, "好友请求已发送给 #{user_name}")}

        {:error, changeset} ->
          IO.puts("=== 创建关系失败 ===")
          IO.inspect(changeset.errors, label: "错误信息")

          # 检查具体的错误类型并显示相应信息
          error_message = case changeset.errors do
            errors when is_list(errors) ->
              cond do
                Keyword.has_key?(errors, :user_b_id) and
                String.contains?(inspect(Keyword.get(errors, :user_b_id)), "不能添加自己为好友") ->
                  "不能添加自己为好友"

                Keyword.has_key?(errors, :user_a_id) or Keyword.has_key?(errors, :user_b_id) ->
                  # 检查是否是待处理的好友请求
                  case UserRelationship.get_user_relationship_by_users(current_user_id, friend_id) do
                    %{relationship_status: "pending"} ->
                      "已经添加过好友请求请等待同意"
                    _ ->
                      "该好友关系已存在"
                  end

                true ->
                  "发送好友请求失败，请重试"
              end
            _ ->
              "发送好友请求失败，请重试"
          end

          {:noreply, show_notification(socket, :error, error_message)}
      end
    end
  end

  # 显示通知的辅助函数
  defp show_notification(socket, type, message) do
    assign(socket,
      show_notification: true,
      notification_type: type,
      notification_message: message
    )
  end


    # 处理定时器自动隐藏通知
  def handle_info(:hide_notification, socket) do
    {:noreply, assign(socket,
      show_notification: false,
      notification_timer: nil
    )}
  end

  # 隐藏通知
  def handle_event("hide_notification", _params, socket) do
    # 如果有定时器，取消它
    if socket.assigns[:notification_timer] do
      Process.cancel_timer(socket.assigns.notification_timer)
    end

    {:noreply, assign(socket,
      show_notification: false,
      notification_timer: nil
    )}
  end



  # 显示好友请求模态框
def handle_event("show_friend_requests", _params, socket) do
  current_user_id = socket.assigns.user_id

  # 一次查询获取所有需要的数据
  friend_requests = UserRelationship.get_pending_relationships_with_user_info(current_user_id)

  {:noreply, assign(socket,
    friends_requests_modal: true,
    friend_requests: friend_requests
  )}
end


# 关闭好友请求模态框
def handle_event("close_friend_requests_modal", _params, socket) do
  {:noreply, assign(socket, friends_requests_modal: false)}
end

# 同意好友请求
def handle_event("accept_friend_request", %{"request-id" => request_id,"user-a-id" => requester_id} = _params, socket) do
  case UserRelationship.accept_user_relationship(request_id) do
    {:ok, :accepted} ->
      current_user_id = socket.assigns.user_id

      # 向请求发送方广播好友请求被接受的通知
      Phoenix.PubSub.broadcast(
        EliPhxPlay.PubSub,
        "user_notifications:#{requester_id}",
        {:friend_request_accepted, %{accepted_by_user_id: current_user_id}}
      )

      # 重新获取好友请求列表
      friend_requests = UserRelationship.get_pending_relationships_with_user_info(current_user_id)

      # 重新计算待处理请求数量
      pending_count = length(friend_requests)

      # 通知父组件更新数据
      send(self(), {:update_pending_count, pending_count})

      send(self(), {:update_contacts})

      {:noreply,
        socket
        |> assign(friend_requests: friend_requests)
        |> assign(pendingnum: pending_count)
        |> show_notification(:success, "已同意好友请求")}

    {:error, _reason} ->
      {:noreply, show_notification(socket, :error, "操作失败，请重试")}
  end
end



# 拒绝好友请求
def handle_event("reject_friend_request", %{"request-id" => request_id}, socket) do
  case UserRelationship.update_relationship_status(request_id, "rejected") do
    {:ok, _relationship} ->
      current_user_id = socket.assigns.user_id

      # 重新获取好友请求列表
      friend_requests = UserRelationship.get_pending_relationships_with_user_info(current_user_id)

      # 重新计算待处理请求数量
      pending_count = length(friend_requests)

      # 通知父组件更新数据
      send(self(), {:update_pending_count, pending_count})

      {:noreply,
        socket
        |> assign(friend_requests: friend_requests)
        |> assign(pendingnum: pending_count)
        |> show_notification(:success, "已拒绝好友请求")}

    {:error, _changeset} ->
      {:noreply, show_notification(socket, :error, "操作失败，请重试")}
  end
end



# 处理新的好友请求通知
def handle_info({:new_friend_request, %{from_user_id: from_user_id, relationship_id: _relationship_id}}, socket) do
  current_user_id = socket.assigns.user_id

  # 重新计算待处理请求数量
  pending_count = UserRelationship.get_pending_relationships_count(current_user_id)

  # 如果好友请求模态框是打开的，也更新请求列表
  friend_requests = if socket.assigns.friends_requests_modal do
    UserRelationship.get_pending_relationships_with_user_info(current_user_id)
  else
    socket.assigns.friend_requests
  end

  # 通知父组件更新数据
  send(self(), {:update_pending_count, pending_count})

  # 获取发送方用户信息用于通知
  sender_info = case Accounts.get_user(from_user_id) do
    %{nickname: nickname} when nickname != nil -> nickname
    %{account: account} -> account
    _ -> "某用户"
  end

  {:noreply,
    socket
    |> assign(pendingnum: pending_count)
    |> assign(friend_requests: friend_requests)
    |> show_notification(:success, "#{sender_info} 向您发送了好友请求")}
end


# 处理好友请求被接受的通知
def handle_info({:friend_request_accepted, %{accepted_by_user_id: accepted_by_user_id}}, socket) do
  # 获取接受方用户信息
  accepter_info = case Accounts.get_user(accepted_by_user_id) do
    %{nickname: nickname} when nickname != nil -> nickname
    %{account: account} -> account
    _ -> "某用户"
  end

  # 通知父组件更新联系人列表
  send(self(), {:update_contacts})

  {:noreply, show_notification(socket, :success, "#{accepter_info} 已接受您的好友请求")}
end


end
